package com.lupus.business;


import java.util.*;
import javax.servlet.http.*;
import java.sql.Connection;
import com.lupus.common.ConnectionFactory;

public abstract class Business {
	public static String BUSINESSPATHPREFIX = "com.lupus.business.inspector.";
	private Connection connection = null;
	private Inspectable inspector = null;
	public static Business getConcreteBusiness(Map<String,Object> requestMap){
		return new CommonBusiness();
	}
	
	protected boolean beforePerformAction(Map<String,Object> requestMap,Map<String,Object> responseMap,HttpServletRequest request,HttpServletResponse response)throws Exception{
		boolean preInspectResult = true;
		Map<String,Object> actionMap = (Map)requestMap.get("requestAction");
		String inspectorName = (String)actionMap.get("inspectorName");
		if(inspectorName!=null&&inspectorName.length()>0){
			Class clazz = Thread.currentThread().getContextClassLoader().loadClass(BUSINESSPATHPREFIX+inspectorName);
			inspector = (Inspectable)clazz.newInstance();
			preInspectResult = inspector.preInspect(requestMap,responseMap,request,response);
		}
		return preInspectResult;
	}
	
	public Map<String,Object> perform (Map<String,Object> requestMap,HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> responseMap = new ResponseMap(requestMap);
		connection = ConnectionFactory.getConnection();
		response.setContentType("text/html; charset=UTF-8");
		response.setHeader("Pragma","No-cache");
		response.setHeader("Cache-Control","no-cache");
		response.setDateHeader("Expires",0);
		try{
			if(beforePerformAction(requestMap,responseMap,request,response)){
				responseMap = concreatePerform(requestMap,responseMap,connection);
				afterPerformAction(requestMap,responseMap,request,response);
			}
		}catch(Exception e){
			throw new RuntimeException(e);
		}
		return responseMap;
	}
	
	protected void afterPerformAction(Map<String,Object> requestMap,Map<String,Object> responseMap,HttpServletRequest request,HttpServletResponse response){
		if(inspector!=null){
			inspector.sufInspect(requestMap,responseMap,request,response);
		}
	}
	
	protected abstract Map<String,Object> concreatePerform(Map<String,Object> requestMap,Map<String,Object> responseMap,Connection connection)throws Exception;
}
